package io.gitee.zhangbinhub.admin.workflow.component

import cn.dev33.satoken.stp.StpUtil
import io.gitee.zhangbinhub.acp.core.common.CommonTools
import io.gitee.zhangbinhub.admin.common.constant.WorkFlowConstant
import io.gitee.zhangbinhub.admin.resource.server.feign.CommonOauthServer
import org.dromara.warm.flow.core.handler.PermissionHandler
import org.springframework.stereotype.Component

@Component
class WorkFlowPermissionHandler(private val commonOauthServer: CommonOauthServer) : PermissionHandler {
    fun userIdList(permissionList: List<String>): Set<String> = permissionList.map { permission ->
        when {
            permission.startsWith(WorkFlowConstant.PERMISSION_ROLE_PREFIX) -> {
                permission.substring(WorkFlowConstant.PERMISSION_ROLE_PREFIX.length).let { roleId ->
                    commonOauthServer.findRoleById(roleId).userIds
                }
            }

            permission.startsWith(WorkFlowConstant.PERMISSION_DEPT_PREFIX) -> {
                permission.substring(WorkFlowConstant.PERMISSION_DEPT_PREFIX.length).let { organizationId ->
                    commonOauthServer.findOrgById(organizationId).userIds
                }
            }

            else -> listOf(permission.trim())
        }
    }.flatten().toSet()

    fun permissions(userIdList: List<String>): Set<String> = commonOauthServer.findUserList(userIdList).map { user ->
        mutableListOf<String>().apply {
            this.add(user.id!!)
            user.roleSet.forEach { role ->
                this.add("${WorkFlowConstant.PERMISSION_ROLE_PREFIX}${role.id}")
            }
            user.organizationSet.forEach { organization ->
                this.add("${WorkFlowConstant.PERMISSION_DEPT_PREFIX}${organization.id}")
            }
        }
    }.flatten().toSet()

    override fun permissions(): MutableList<String> = mutableListOf<String>().apply {
        commonOauthServer.findUserByLoginNo(StpUtil.getLoginIdAsString()).let {
            if (!CommonTools.isNullStr(it.id)) {
                permissions(listOf(it.id!!))
            } else {
                mutableListOf()
            }
        }
    }

    override fun getHandler(): String? =
        commonOauthServer.findUserByLoginNo(StpUtil.getLoginIdAsString()).id
}